import 'package:flutter/material.dart';
import 'package:reorderables/reorderables.dart';
import 'dart:math' as math;

void main() {
  runApp(const MaterialApp(home: MyApp()));
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with SingleTickerProviderStateMixin {
  final double _iconSize = 90;
  late List<Widget> _tiles;
  late List<num> _arr;

  // 动画控制器
  late AnimationController _animationController;
  // 标记动画是否正在运行，默认设置为false
  bool _isAnimating = false;

  @override
  void initState() {
    super.initState();

    // 初始化动画控制器，设置动画时长为100毫秒
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 100),
      value: 0.5,
      vsync: this,
    );

    // _animationController.repeat(reverse: true);

    _arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

    _tiles = _arr.map((element) {
      var result = AnimatedBuilder(
        animation: _animationController,
        builder: (context, child) {
          // 使用Transform.rotate实现旋转效果
          // 通过动画值控制旋转角度，实现抖动效果
          return Transform.rotate(
            // 将动画值映射到-5度到5度之间，产生抖动效果
            angle: (math.pi / 180) * (10 * _animationController.value - 5),
            child: child,
          );
        },
        // 这是要抖动的图标
        child: Text('序号：' + element.toString()),
      );

      return result;
    }).toList();
  }

  /// 开始动画
  void _startAnimation() {
    if (!_isAnimating) {
      // _animationController.value = 5;
      _animationController.repeat(reverse: true);
      setState(() {
        _isAnimating = true;
      });
    }
  }

  /// 停止动画
  void _stopAnimation() {
    if (_isAnimating) {
      _animationController.value = 0.5;

      // 停止动画
      _animationController.stop();

      setState(() {
        _isAnimating = false;
      });
    }
  }

  //////////////////////////////////////////////
  @override
  Widget build(BuildContext context) {
    // 拖拽成功回调
    void _onReorder(int oldIndex, int newIndex) {
      setState(() {
        _stopAnimation();

        Widget row = _tiles.removeAt(oldIndex);
        _tiles.insert(newIndex, row);

        debugPrint(
            '${DateTime.now().toString().substring(5, 22)} reorder 完成. index:$newIndex');
      });
    }

    var wrap = ReorderableWrap(
        spacing: 8.0,
        runSpacing: 4.0,
        padding: const EdgeInsets.all(8),
        children: _tiles,
        onReorder: _onReorder,
        onNoReorder: (int index) {
          _stopAnimation();
          // 拖动取消 （没有拖拽到合适位置）
          //this callback is optional
          debugPrint(
              '${DateTime.now().toString().substring(5, 22)} reorder cancelled. index:$index');
        },
        onReorderStarted: (int index) {
          _startAnimation();
          // 开始拖动
          //this callback is optional
          debugPrint(
              '${DateTime.now().toString().substring(5, 22)} reorder started: index:$index');
        });

    var column = Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        wrap,
        // ButtonBar(
        //   alignment: MainAxisAlignment.start,
        //   children: <Widget>[
        //     IconButton(
        //       iconSize: 50,
        //       icon: Icon(Icons.add_circle),
        //       color: Colors.deepOrange,
        //       padding: const EdgeInsets.all(0.0),
        //       onPressed: () {
        //         var newTile = Icon(Icons.filter_9_plus, size: _iconSize);
        //         setState(() {
        //           _tiles.add(newTile);
        //         });
        //       },
        //     ),
        //     IconButton(
        //       iconSize: 50,
        //       icon: Icon(Icons.remove_circle),
        //       color: Colors.teal,
        //       padding: const EdgeInsets.all(0.0),
        //       onPressed: () {
        //         setState(() {
        //           _tiles.removeAt(0);
        //         });
        //       },
        //     ),
        //   ],
        // ),
      ],
    );

    return SingleChildScrollView(
      child: column,
    );
  }
}
